﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;
using System.Text;
using System.IO;


public partial class Hospital_BackGoods_detail : System.Web.UI.Page
{
    string strSql, BackPlanId, Accountid_yy, buystate;
    protected void Page_Load(object sender, EventArgs e)
    {
        BackPlanId = SysFun.IsSQL(SysFun.ToTrim(Request.QueryString["BackPlanId"]));
        // projectid = SysFun.ToTrim(Request.QueryString["projectid"]); 2007/08/21  马


        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumHospitale);

        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            Accountid_yy = SysFun.ToTrim(_Account.AccountId);
            LabHospital.Text = _Account.DWName;
            if (!IsPostBack)
            {
                labSubmit.Text = "<input id=\"Submit1\" type=\"submit\" value=\"提交退货单\" name=\"PullPruList\" onclick=\"javascript:return confirm('确认将该退货单提交给配送人吗？提交后无法修改和新增退货药品');\" class=\"button_bg6\" style=\"width: 90px\" />";
                // labLink.Text = "<a target='_blank'  href='BackGoodslist.aspx?BackPlanId=" + BackPlanId + "&projectid=" + projectid + "'> <img style='border-top-style: none; border-right-style: none; border-left-style: none; border-bottom-style: none' src='../Images/tuihuo.gif' /></a> ";
                // 2007/08/21  马

                labLink.Text = "<a target='_blank'  href='BackGoodslist.aspx?BackPlanId=" + BackPlanId + "'> <img style='border-top-style: none; border-right-style: none; border-left-style: none; border-bottom-style: none' src='../Images/tuihuo.gif' /></a> ";

                labDel.Text = "<input type='submit' name='btnSubmit' value='删除' class='button_bg'   onclick=\"javascript:if(confirm('确定真的要删除吗？？？？ ')){return CheckForm1();}else {return false;}\" id='Submit3'/>";
                labSave.Text = "<input  type='submit' name='butSave' class='button_bg8'  style='width:121px' value='保存退货量' onclick=\"javascript:return checkValue()\" />";
                Db db = new Db();
                System.Data.IDataReader dr;
                strSql = "select * from BackPlan where BackPlanId=" + BackPlanId + " and AccountId_YY=" + _Account.AccountId;
                dr = db.DataReader(strSql);
                if (dr.Read())
                {
                    txtStartTime.Text = Convert.ToDateTime(dr["StartTime"]).ToShortDateString();
                    txtPlanName.Text = SysFun.ToTrim(dr["PlanName"]);
                    rdoBuyStatus.SelectedValue = SysFun.ToTrim(dr["BuyStatus"]);
                    txtRemarks.Text = SysFun.ToTrim(dr["Remarks"]);
                    buystate = SysFun.ToTrim(dr["BuyStatus"]);
                    if (SysFun.ToInt(dr["BuyStatus"]) == 2)
                    {
                        labLink.Text = "";
                        labSubmit.Text = "";
                        labDel.Text = "";
                        labSave.Text = "";
                    }
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                }
                else
                {
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                    Response.Write("对不起，你没有权限浏览不属于自身采购单的药品");
                    Response.Redirect("../HomePage/Default.aspx");
                }
                dr = null;
                db = null;

            }

            //<!--删除退货药品

            if (Request.Form["btnSubmit"] == "删除" && Request.Form["chk"] != null)
            {
                string BackPlanGoodsId = "";
                BackPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);
                Db db = new Db();
                if (buystate == "2")
                {
                    db.Close();
                    Response.Write("<script>window.alert('对不起，采购单已经提交给配送人，不可删除！');</script>");
                }
                else
                {
                    if (BackPlanGoodsId != "")
                    {
                        string[] BGID = BackPlanGoodsId.Length == 0 ? new string[] { "" } : BackPlanGoodsId.Substring(0).Split(new char[] { ',' });

                        strSql = "";
                        for (int i = 0; i < BGID.Length; i++)
                        {
                            //获取buyplangoodsid
                            string buyplanGoodsID = Request.Form["BuyPlanGoodsId" + BGID[i].ToString()].ToString();
                            //删除药品时，将药品的退货态更新为可选0
                            strSql += "@" + "update buyplangoods set ReturnState =0 where BuyPlanGoodsId =" + buyplanGoodsID;
                            strSql += "@" + "delete  from BackPlanGoods  where BackPlanGoodsId=" + BGID[i].ToString() + " and (BackState=0 or  BackState is null) ";
                        }
                        if (strSql.Length > 0)
                        {
                            HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "删除", "BackPlanGoods", strSql, "../Hospital/BackGoods_detail.aspx");
                            db.ExecuteTransaction(strSql.Substring(1).Split(new char[] { '@' }), 30);
                        }
                    }
                    db.Close();
                }
            }
            //删除退货药品-->

            //<!--保存退货量
            if (Request.Form["butSave"] == "保存退货量")
            {
                string BackPlanGoodsId = "", caigoushu;
                //BackPlanGoodsId = SysFun.ToTrim(Request.Form["BackPlanGoodsId"]);
                //caigoushu = Request.Form["BackNum"];
                BackPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);
                Db db = new Db();

                //是否已提交




                if (BackPlanGoodsId != "")
                {
                    string[] SGID = BackPlanGoodsId.Length == 0 ? new string[] { "" } : BackPlanGoodsId.Substring(0).Split(new char[] { ',' });
                    //string[] CNum = caigoushu.Length == 0 ? new string[] { "" } : caigoushu.Substring(0).Split(new char[] { ',' });
                    strSql = "";
                    for (int i = 0; i < SGID.Length; i++)
                    {
                        if (SGID[i].ToString().Trim().Length != 0)
                        {
                            string BackNum = Request.Form["BackNum" + SGID[i].ToString()].ToString();
                            //string batchnumber = Request.Form["batchnum" + SGID[i].ToString()].ToString();
                            //string validityDate = Request.Form["validityDate" + SGID[i].ToString()].ToString();
                            string backBecause = Request.Form["DropDownList" + SGID[i].ToString()].ToString();


                            // strSql += "@" + "update BackPlanGoods set BackNum=" + SysFun.ToInt(BackNum) + ",batchnumber='" + batchnumber + "',validityDate='" + validityDate + "',BackBecause='" + backBecause + "' where BackPlanGoodsId=" + SGID[i].ToString();

                            strSql += "@" + "update BackPlanGoods set BackNum=" + SysFun.ToInt(BackNum) + ",BackBecause='" + backBecause + "' where BackPlanGoodsId=" + SGID[i].ToString();
                        }
                    }
                    if (strSql.Length > 0)
                    {
                        HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "BackPlanGoods", strSql, "../Hospital/BackGoods_detail.aspx");
                        db.ExecuteTransaction(strSql.Substring(1).Split(new char[] { '@' }), 30);
                    }
                }
                db.Close();
            }
            //保存退货量-->

            if (Request.Form["PullPruList"] == "提交退货单")
            {
                string str;
                str = "select * from Backplan where BackPlanId=" + BackPlanId + " and BuyStatus=0";
                Db db = new Db();
                System.Data.IDataReader dr;
                dr = db.DataReader(str);
                if (dr.Read())
                {
                    Response.Write("<script>window.alert('对不起，你还未退货药品，不能提交采购单');window.history.back(0);</script>");
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                    return;
                }
                dr.Close();
                dr.Dispose();


                str = "select * from BackPlanGoods where (BackNum=0 or  BackNum is null)  and BackPlanId=" + BackPlanId;
                //Response.Write(str);
                //Response.End();
                dr = db.DataReader(str);
                if (dr.Read())
                {
                    Response.Write("<script>window.alert('对不起，有退货量为0的药品，不能提交采购单');window.history.back(0);</script>");
                    dr.Close();
                    dr.Dispose();
                    db.Close();
                    return;
                }
                dr.Close();
                dr.Dispose();
                db.Close();
                str = "update Backplan set BuyStatus='2'   where BackPlanId=" + BackPlanId;
                Db db1 = new Db();
                db1.Command(str);
                HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "Backplan", str, "../Hospital/BackGoods_detail.aspx");
                Response.Write("<script>window.alert('提交成功');window.opener.location.reload();window.close();</script>");
                db1.Close();
                showGridView();
            }
            showGridView();

        }
    }

    public void showGridView()
    {
        int i = 0;
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "BackGoodsView";                                               //要查询的表明
        dbPage.Key = "BackPlanGoodsId";                                         //表的主键    
        dbPage.Where = strcheck();                                                  //查询条件    
        dbPage.SelectField = "PurchasePrice,remark,Case isnull(BackState,0) When 0 Then '未确认退货' WHEN 1 Then '确认退货' END AS BackState,BackPlanGoodsId,BuyPlanGoodsId,InflowNum,BackNum,GoodsNum,SupplyGoodsId,GoodsId,Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '确认送货' WHEN '2' then '确认入库' WHEN '3' then '退货' END AS DealStatus,ProductCode,ProductName,MedicineModel,Outlookc,ProjectId,Factor,UserCode_SC,CompanyName_SC,CompanyName_TB,UserCode_PS,CompanyName_PS,TradePrice,Case GoodsState When '0' Then '原挂网' WHEN '1' Then '备案采购商品' WHEN '2' then '不限价不竞价商品' END AS GoodsState,GoodsName,Outlookc+'×'+convert(varchar(20),Factor)+unit As Pack1,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " end as QualityLevels,batchnumber,CONVERT(varchar(100), validityDate, 23) as validityDate,BackBecause,inflownumstock";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 20;                                                    //没有显示记录条数   
        dbPage.OrderBy = "ProductName,BackPlanGoodsId";//排序字段
        System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
        strHtml.Append("<table width='100%'id='tabData1' name='tabData1' border='0' align='right' style='text-align:center;' cellpadding='2' cellspacing='1'>");
        strHtml.Append("<tr>");
        strHtml.Append("<td width='5%'>商品<br/>流水号</td>");
        strHtml.Append("<td  width='5%'>通用名</td>");
        strHtml.Append("<td  width='5%'>商品名</td>");
        strHtml.Append("<td  width='5%'>剂型</td>");
        //  strHtml.Append("<td  width='5%'>转换<br/>系数</td>");
        strHtml.Append("<td  width='3%'>包装<br/>规格</td>");
        strHtml.Append("<td  width='3%'>备注</td>");
        strHtml.Append("<td  width='5%'>质量<br/>层次</td>");
        strHtml.Append("<td  width='5%'>交易价</td>");
        strHtml.Append("<td  width='5%'>退货量</td>");
        strHtml.Append("<td  width='9%'>退货<br/>批号</td>");
        strHtml.Append("<td  width='9%'>有效期</td>");
        strHtml.Append("<td width='9%' >退货<br/>原因</td>");
        strHtml.Append("<td width='5%' >退货<br/>状态</td>");
        strHtml.Append("<td  width='5%'>生产企业<br/>编号</td>");
        strHtml.Append("<td  width='5%'>生产企业</td>");
        strHtml.Append("<td  width='5%'>配送企业<br/>编号</td>");
        strHtml.Append("<td  width='5%'>配送企业</td>");
        //strHtml.Append("<td  >交易状态</td>");
        //strHtml.Append("<td  >采购目录状态</td>");

        strHtml.Append("<td  width='5%'>采购量</td>");
        strHtml.Append("<td width='5%' >实际<br/>入库量</td>");
        strHtml.Append("<td  width='5%'>采购<br/>总金额</td>");


        strHtml.Append("<td width='5%'>选择</td>");
        strHtml.Append("</tr>");
        System.Data.IDataReader dr = dbPage.ExecuteReader();
        string _strBackState = "";
        while (dr.Read())
        {
            if (i == 0)
            {
                strHtml.Append("<tr class='table_td'>");
                i++;
            }
            else
            {
                strHtml.Append("<tr class='table_td2'>");
                i--;
            }
            strHtml.Append("<td width='8%'>" + dr["GoodsId"].ToString() + "</td>");

            strHtml.Append("<td width='8%'>" + dr["ProductName"].ToString() + "</td>");
            strHtml.Append("<td width='5%'>" + dr["GoodsName"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["Medicinemodel"].ToString() + "</td>");
            // strHtml.Append("<td width='5%'>" + dr["Factor"].ToString() + "</td>");
            strHtml.Append("<td width='3%'>" + dr["Pack1"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["remark"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["QualityLevels"].ToString() + "</td>");
            strHtml.Append("<td><input type='hidden' name='BuyPlanGoodsId" + dr["BackPlanGoodsId"].ToString() + "' value='" + dr["BuyPlanGoodsId"].ToString() + "'>" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "</td>");
            _strBackState = dr["BackState"].ToString();
            if (_strBackState == "未确认退货")
            {
                strHtml.Append("<td title='最大可退量为：" + dr["inflownumstock"] + "'><input type='hidden' name='BackPlanGoodsId' value='" + dr["BackPlanGoodsId"].ToString() + "'><input type='text' size=8 name='BackNum" + dr["BackPlanGoodsId"].ToString() + "' id='BackNum" + dr["BackPlanGoodsId"].ToString() + "' onblur=\"javascript:if(!/^[0-9]*[1-9][0-9]*$/.test(this.value)){alert('请输入正确数量！');this.value=" + SysFun.ToTrim(dr["BackNum"]) + "};if(this.value>" + SysFun.ToTrim(dr["inflownumstock"]) + "){alert('退货数量不能大于入库数量！');this.value=" + SysFun.ToTrim(dr["BackNum"]) + "}\" NumericOnly='BackNum' NotNull='BackNum'  value='" + SysFun.ToTrim(dr["BackNum"]) + "' ></td>");
            }
            else
            {
                strHtml.Append("<td>" + dr["BackNum"].ToString() + "</td>");
            }

            //if (_strBackState == "未确认退货")
            //{
            //    strHtml.Append("<td><input type='text' NotNull='药品批号'  id='batchnum" + dr["BackPlanGoodsId"].ToString() + "' name='batchnum" + dr["BackPlanGoodsId"].ToString() + "' value='" + dr["batchnumber"].ToString() + "'></td>");
            //}
            //else
            //{
            strHtml.Append("<td>&nbsp;" + dr["batchnumber"].ToString() + "</td>");
            //}
            //if (_strBackState == "未确认退货")
            //{
            //    strHtml.Append("<td><input type='text' NotNull='药品有效期' id='validityDate" + dr["BackPlanGoodsId"].ToString() + "' name='validityDate" + dr["BackPlanGoodsId"].ToString() + "' value='" + dr["validityDate"].ToString() + "'onclick='javascript:fPopCalendar(this,this);'></td>");
            //}
            //else
            //{
            strHtml.Append("<td>&nbsp;" + dr["validityDate"].ToString() + "</td>");
            //}

            if (_strBackState == "未确认退货")
            {
                //  strHtml.Append("<td><input type='text' NotNull='退货原因' id='BackBecause" + dr["BackPlanGoodsId"].ToString() + "' name='BackBecause" + dr["BackPlanGoodsId"].ToString() + "' value='" + dr["BackBecause"].ToString() + "'></td>");
                strHtml.Append("<td> <select name=\"DropDownList" + dr["BackPlanGoodsId"].ToString() + "\" id=\"DropDownList" + dr["BackPlanGoodsId"].ToString() + "\"><option value=\"破损\" " + GetSelected(dr["BackBecause"].ToString(), "破损") + ">破损</option><option value=\"混批\" " + GetSelected(dr["BackBecause"].ToString(), "混批") + " >混批</option><option value=\"其他\" " + GetSelected(dr["BackBecause"].ToString(), "其他") + ">其他</option></select></td>");

            }
            else
            {
                strHtml.Append("<td>&nbsp;" + dr["BackBecause"].ToString() + "</td>");
            }

            strHtml.Append("<td>" + _strBackState + "</td>");
            strHtml.Append("<td>" + dr["UserCode_SC"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["CompanyName_SC"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["UserCode_PS"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["CompanyName_PS"].ToString() + "</td>");
            //strHtml.Append("<td>" + dr["DealStatus"].ToString() + "</td>");
            //strHtml.Append("<td>" + dr["GoodsState"].ToString() + "</td>");

            strHtml.Append("<td>" + SysFun.ToTrim(dr["GoodsNum"]) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["InflowNum"]) + "</td>");
            strHtml.Append("<td>" + dr["PurchasePrice"].ToString() + "</td>");

            if (_strBackState == "未确认退货")
            {
                strHtml.Append("<td><input name='chk' id='chk' type='checkbox' value='" + dr["BackPlanGoodsId"].ToString() + "'></td>");
            }
            else
            {
                strHtml.Append("<td></td>");
            }
            strHtml.Append("</tr>");
        }
        strHtml.Append("</table>");
        Lablist.Text = strHtml.ToString();

        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键

    }

    private string strcheck()  //查询条件
    {
        // string _strTemp = " projectid=" + projectid + " and BackPlanId=" + BackPlanId + " and Accountid_YY=" + Accountid_yy;
        //2007/08/21  马

        string _strTemp = " BackPlanId=" + BackPlanId + " and Accountid_YY=" + Accountid_yy;

        string _strProductName, _strCompanyName_SC, _strCompanyName_SC_usercoder, _strCompanyName_PS, _strCompanyname_PS_usercoder;

        //商品流水号

        string _strGoodsId = txtGoodsId.Text.ToString();
        if (_strGoodsId != "")
        {
            _strTemp += " and GoodsId = " + _strGoodsId;
        }

        //药品名称或拼音码
        _strProductName = txtProductName.Text.ToString().Trim();
        if (_strProductName != "")
        {
            _strTemp = _strTemp + " and (ProductName like '%" + _strProductName + "%' or Product_SpellingCode like '%" + _strProductName + "%')";
        }

        //生产企业名称
        _strCompanyName_SC = textCompanyName_SC.Text.ToString().Trim();
        if (_strCompanyName_SC != "")
        {
            _strTemp = _strTemp + " and CompanyName_SC like '%" + _strCompanyName_SC + "%'";
        }
        //生产企业编码
        _strCompanyName_SC_usercoder = Textuscoder_sc.Text.ToString().Trim();
        if (_strCompanyName_SC_usercoder != "")
        {
            _strTemp = _strTemp + " and UserCode_SC like '%" + _strCompanyName_SC_usercoder + "%'";
        }


        //配送企业名称

        _strCompanyName_PS = TextCompanyName_PS.Text.ToString().Trim();
        if (_strCompanyName_PS != "")
        {
            _strTemp = _strTemp + " and CompanyName_PS like '%" + _strCompanyName_PS + "%'";
        }
        //配送企业编码

        _strCompanyname_PS_usercoder = Textuscoder_ps.Text.ToString().Trim();
        if (_strCompanyname_PS_usercoder != "")
        {
            _strTemp = _strTemp + " and UserCode_PS like '%" + _strCompanyname_PS_usercoder + "%'";
        }

        //退货量
        string _strBackNum = txtGoodsNum.Text.ToString();
        if (_strBackNum != "")
        {
            if (_strBackNum == "0")
            {
                _strTemp = _strTemp + " and (BackNum=0 or BackNum is null) ";
            }
            else
            {
                _strTemp = _strTemp + " and BackNum=" + _strBackNum;
            }
        }
        return _strTemp;
    }
    /// <summary>
    ///  自动选择退货原因
    /// </summary>
    /// <param name="_strBackreson">库中原因</param>
    /// <param name="_stroption">原来列表列</param>
    /// <returns></returns>
    private string GetSelected(string _strBackreson, string _stroption)
    {
        if (_strBackreson.Contains(_stroption)) return "selected=\"selected\"";
        else return "";
    }




    protected void Button2_Click(object sender, EventArgs e)
    {
        BindDate();
        if (this.GridView1.Rows.Count > 0)
        {
            this.GridView1.Visible = true;// 如果输出为Word，修改为以下代码 
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("Content-Disposition", "inline;filename=test.xls");
            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            sb.Append("<html><body>");
            this.GridView1.RenderControl(hw);
            sb.Append("</body></html>");
            Response.Write(sb.ToString());
            Response.End();
            this.GridView1.DataSource = null;
            this.GridView1.Dispose();
        }
        else
        {
            Response.Redirect("<script>window.alert('没有信息,无法打印!')</script>");
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }



    public void BindDate()
    {

        string sql = "select GoodsId  as '商品流水号',ProductName as '通用名',GoodsName as '商品名',Medicinemodel as '剂型',Outlookc+'×'+convert(varchar(20),Factor)+unit As '包装规格',remark as 备注,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " end  as '质量层次',TradePrice as '交易价',BackNum as '退货量',BackBecause as 退货原因,batchnumber as '批号',validityDate as '有效期',BackBecause as '退货原因',Case BackState When '0' Then '未确认退货' WHEN '1' Then '确认退货' END   as '退货状态',UserCode_SC as '生产企业编号',CompanyName_SC as '生产企业',UserCode_PS as '配送企业编号',CompanyName_PS as '配送企业',GoodsNum as '采购量',InflowNum as '实际入库量',PurchasePrice  as '采购总金额' from BackGoodsView" +
               " where " + strcheck();


        Db db = new Db();

        System.Data.DataTable dr = db.DataTable(sql);
        this.GridView1.DataSource = dr;
        this.GridView1.DataBind();

        dr.Dispose();
        db.Close();
    }
}

